package com.qding.park.manager.web.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qding.park.common.core.annotation.log.OperationLogType;
import com.qding.park.common.core.annotation.log.SystemControllerLog;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.system.SystemUnKnown;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.export.DataField;
import com.qding.park.common.utils.export.ExportDataSource;
import com.qding.park.common.utils.export.excel.ExcelDataExportor;
import com.qding.park.common.utils.export.excel.MODE;
import com.qding.park.common.web.controller.BaseController;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.common.rest.domain.AnswerMsg;
import com.qding.park.manager.common.rest.domain.AnswerMsgFactoryImpl;
import com.qding.park.manager.common.rest.enums.ResponseCodeEnum;
import com.qding.park.manager.facade.statis.service.TempPayStatisFacade;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.example.NcTempPayExample;
import com.qding.park.manager.pojo.noncore.NcTempPayInfo;
import com.qding.park.manager.web.form.TempPayListForm;
import com.qding.park.manager.web.power.Power;

/**
 * @ClassName: Web_TempPayController
 * @Description: 临停缴费单统计
 * @author Comsys-Administrator
 * @date 2016年10月12日 上午10:02:09
 *
 */
@RestController
@RequestMapping("/tempPayOrder")
public class Web_TempPayController extends BaseController {
    private static final Logger _log = LoggerFactory.getLogger(Web_TempPayController.class);

	@Autowired
	private TempPayStatisFacade tempPayStatisFacade;

	@Power(visitPark = "#form.getParkId()")
	@SystemControllerLog(description = "临停缴费查询", operation = OperationLogType.tempPayOrder_list)
	@RequestMapping("/list")
	public AnswerMsg list(@Valid TempPayListForm form, BindingResult result) {

		/* 解析验证结果 */
		super.analysisValid(result);
		/* 解析验证结果 */
		PowerInfo power = this.getPowerInfo();

		int jumpPageInt = Integer.valueOf(form.getJumpPage());
		int pageLengthInt = Integer.valueOf(form.getPageLength());
		/* 组装统计条件 */
		NcTempPayExample example = new NcTempPayExample();
		if (!StringUtils.isBlank(form.getCarNum())) {
			example.setCarNum(form.getCarNum());
		}
		if (!StringUtils.isBlank(form.getParkId())) {
			example.setParkId(form.getParkId());
		}
		if (!power.isAdminIs()) {
			example.setInParks(power.getParkList());
		}
		/* 组装统计条件 */

		/***** 统计查询 *******/
		ParkDataResult dataResult = tempPayStatisFacade.list(example, jumpPageInt, pageLengthInt);
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
		return answerMsg;
	}

	@Power(visitPark = "#parkId")
	@SystemControllerLog(description = "临停缴费导出", operation = OperationLogType.tempPayOrder_exportExcel)
	@RequestMapping("/exportExcel")
	@ResponseBody
	public AnswerMsg exportExcel(String startTime, String endTime, String parkId) {

		try {
			PowerInfo power = this.getPowerInfo();

			final NcTempPayExample example = new NcTempPayExample();

			if (!StringUtils.isBlank(startTime)) {
				// example.setStartTime(startTime);
				example.setStartTime(DateUtils.parseDate(startTime, DateUtils.DATE_FORMAT_DATETIME));

			}
			if (!StringUtils.isBlank(endTime)) {
				// example.setEndTime(endTime);
				example.setEndTime(DateUtils.parseDate(endTime, DateUtils.DATE_FORMAT_DATETIME));
			}
			if (!StringUtils.isBlank(parkId)) {
				example.setParkId(parkId);
			}
			if (!power.isAdminIs()) {
				example.setInParks(power.getParkList());
			}

			final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
			String filename = "临时缴费单报表_" + sdf2.format(new Date());
			response.setHeader("Content-disposition",
					"attachment; filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
			OutputStream os = response.getOutputStream();
			DataField[] dataFields = new DataField[6];
			dataFields[0] = new DataField("订单号", "orderId", 30);
			dataFields[1] = new DataField("订单状态", "orderStatus", 25);
			dataFields[2] = new DataField("用户账号", "tel", 20);
			dataFields[3] = new DataField("缴费车牌", "carNum", 25);
			dataFields[4] = new DataField("缴费类型", "payType", 30);
			dataFields[5] = new DataField("缴费金额(元)", "realFee", 20);
			
			new ExcelDataExportor<Object>(dataFields, new ExportDataSource<Object>() {
				@Override
				public List getData() {
					// 查询统计条件
					List<NcTempPayInfo> ncTempPayInfos = tempPayStatisFacade.exportExcel(example);
					List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
					int temp = 0;
					for (int i = 0; i < ncTempPayInfos.size(); i++) {
						Map<String, Object> mapParam = new HashMap<String, Object>();
						NcTempPayInfo ncTempPayInfo = ncTempPayInfos.get(i);
						temp = i;
						mapParam.put("orderId", ncTempPayInfo.getPayOrderID());
						if (ncTempPayInfo.getOrderSource() == OrderSourceEnum.OUTLINE.getType()) {
							mapParam.put("orderStatus", ncTempPayInfo.getOutTime() == null ? "成功"
									: (DateUtils.formatDate(ncTempPayInfo.getOutTime(), DateUtils.DATE_FORMAT_DATETIME)
											+ " 成功"));
						} else {
							mapParam.put("orderStatus",
									ncTempPayInfo.getCreate_date() == null ? "成功"
											: (DateUtils.formatDate(ncTempPayInfo.getCreate_date(),
													DateUtils.DATE_FORMAT_DATETIME) + " 成功"));
						}
						// mapParam.put("orderStatus",
						// ncTempPayInfo.getOutTime()==null?"成功":(DateUtils.formatDate(ncTempPayInfo.getOutTime(),DateUtils.DATE_FORMAT_DATETIME)+"
						// 成功"));
						mapParam.put("tel", ncTempPayInfo.getTel());
						mapParam.put("carNum", ncTempPayInfo.getCarNum());
						mapParam.put("payType", OrderSourceEnum.getDescByCode(ncTempPayInfo.getOrderSource()));
						mapParam.put("realFee", ncTempPayInfo.getFeeMoney() / 100);
						lists.add(mapParam);
					}
					return lists;
				}
			}, os, MODE.EXCEL).export();

			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(null);
			return answerMsg;
		} catch (Exception e) {
			SystemUnKnown ex = new SystemUnKnown(e, ExceptionMessage.createExceptionMessage(SystemUnKnown.default_Name,
					"未知Exception", "startTime=" + startTime + ",endTime=" + endTime));
			exceptionHandle.handle(ex);
			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createErrorAnserMsg(ResponseCodeEnum.SYSTEM_ERROR);
			return answerMsg;
		}
	}
}
